package com.blast.cn.ui

import android.text.TextUtils
import android.view.KeyEvent
import com.blast.cn.R
import com.blast.cn.http.MainHttps
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.http.CommonHttpUtil
import com.wxl.common.http.SerialHttpCallback
import com.wxl.common.room.entity.CollectorBean
import com.wxl.common.room.entity.DetonatorEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.serialport.*
import com.wxl.common.util.ObservableUtil
import com.wxl.common.util.StringUtils
import com.wxl.common.util.Toll
import kotlinx.android.synthetic.main.activity_collector_version_layout.*

class UploadCollectorVersionActivity : AbsActivity() {

    var mVersion = 0
    var failTimes = 3
    var loadDialog: LoadingPopupView? = null
    var mDeptNum:String=""

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_collector_version_layout
    }

    override fun onCreateViewChanged() {
        setTopTitle("上传采集器信息")
        SerialPortManager.open(object : SerialPortManager.Companion.OpenPortCallback {
            override fun onOpenPort(state: Int) {
                if (state == 0) {
                    queryCollectorInfo()
                } else {
                    Toll.toll("不能正常打开串口")
                }
            }
        })

        collectVersionCancel.setOnClickListener {
            finish()
        }

        collectVersionSure.setOnClickListener {
            submit()
        }
    }

    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_F1 || keyCode == KeyEvent.KEYCODE_BACK) {
            collectVersionCancel.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_F4 || keyCode == KeyEvent.KEYCODE_ENTER) {
            collectVersionSure.performClick()
        }
        return true
    }

    /**
     * 提交上传
     */
    private fun submit() {
        if (TextUtils.isEmpty(collectVersionCode.text)) {
            Toll.toll("没有获取到采集器编号")
            return
        }
        loadDialog = XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asLoading("正在提交采集器信息...")
        addPop(loadDialog!!.show())
        MainHttps.uploadCollectorInfo(
            collectVersionCode.text.toString(),
            mVersion.toString(),
            object : SerialHttpCallback<String>("") {
                override fun loadDataSuccess(data: String?) {
                    AppContext.appContext.saveCjqTitle(collectVersionCode.text.toString())
                    addCollector()
                }

                override fun loadDataFailed(e: Throwable) {
                    Toll.toll("上传失败")
                }
            })
    }

    private fun addCollector() {
        CommonHttpUtil.getDetonatorInfo(object :
            ObservableUtil.Companion.OnNextCallback<DetonatorEntity>() {
            override fun onNext(t: DetonatorEntity) {
                val c = CollectorBean()
                c.buydept = t.buydept
                c.buydeptid = t.buydeptid
                c.dept = t.dept
                c.deptnum = t.deptnum
                c.createdept = t.deptid
                c.title = collectVersionCode.text.toString()
                c.software_version = mVersion.toString()
                mDeptNum = t.deptnum
                DBHelper.insertCollector(object :
                    ObservableUtil.Companion.OnNextCallback<Boolean>() {
                    override fun onNext(t: Boolean) {
                        loadDialog?.setTitle("正在设置采集器信息...")
                        setCollectorCode()
                    }
                }, c)
            }
        })
    }


    /**
     * 设置采集器厂家代码
     */
    private fun setCollectorCode() {
        if (failTimes <= 0) {
            loadDialog?.dismiss()
            Toll.toll("设置失败")
            return
        }
        Serials.registerSingleStartHexSerial(CmdCode.CJQ_SET_CODE_OK_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                loadDialog?.dismiss()
                Toll.toll("设置成功")
                finish()
            }
        })

        Serials.registerSingleStartHexSerial(CmdCode.CJQ_SET_CODE_E_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                failTimes--
                setCollectorCode()
            }
        })
        SerialPortManager.send(CmdCode.CJQ_SET_CODE_CMD+mDeptNum+"00000000")
    }

    /**
     * 查询采集器信息
     */
    private fun queryCollectorInfo() {
        Serials.registerSingleStartHexSerial(CmdCode.CJQ_READ_INFO_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                parseCollectorInfo(data)
            }
        })
        SerialD.registerCjqSerial(object : Serial() {
            override fun loadReceiveData(data: String) {
                SerialPortManager.send(CmdCode.CJQ_READ_INFO_CMD)//发送获取采集器信息命令
            }
        })
        SerialPortManager.startQueryPortWork()
    }


    /**
     * 解析采集器信息
     */
    private fun parseCollectorInfo(data: String) {
        if (data.length > 31) {
            SerialPortManager.cancelIntervalWork()
            val number: String = data.substring(16, 28)
            mVersion = Integer.valueOf(data.substring(28, 32), 16)
            if (!TextUtils.equals("000000000000", number)) {
                collectVersionCode.text = number
                collectVersionCodeNum.text = StringUtils.getPointVersion(mVersion.toString())
                AppContext.appContext.saveCjqVersion(mVersion.toLong())
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        SerialD.unRegisterCjqSerial()
        SerialPortManager.close()
        SerialPortManager.closePower()
    }
}